const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
const explosionButton = document.querySelector("#explosionButton");

const LEFT = 100;
const TOP = 80;
const WIDTH = 180;
const HEIGHT = 130;

const NUM_EXPLOSION_PAINTERS = 9;
const NUM_FUSE_PAINTERS = 9;

function ImagePainter(imageUrl) {
    this.image = new Image();
    this.image.src = imageUrl;
}
ImagePainter.prototype = {
    image: undefined,

    paint: function(sprite, context) {
        if (this.image !== undefined) {
            if (!this.image.complete) {
                this.image.onload = function(e) {
                    sprite.width = this.width;
                    sprite.height = this.height;

                    context.drawImage(
                        this, // this is image
                        sprite.left,
                        sprite.top,
                        sprite.width,
                        sprite.height
                    );
                };
            } else {
                context.drawImage(
                    this.image,
                    sprite.left,
                    sprite.top,
                    sprite.width,
                    sprite.height
                );
            }
        }
    }
};

const bombPainter = new ImagePainter("bomb.png");
const bombNoFusePainter = new ImagePainter("bomb-no-fuse.png");
let fuseBurningPainters = [];
let explosionPainters = [];

const fuseBurningAnimator = new SpriteAnimator(
    fuseBurningPainters,
    () => (bomb.painter = bombNoFusePainter)
);

const explosionAnimator = new SpriteAnimator(
    explosionPainters,
    () => (bomb.painter = bombNoFusePainter)
);

const bomb = new Sprite("bomb", bombPainter);
explosionButton.onclick = function(e) {
    if (bomb.animating)
        // not now...
        return;

    // burn fuse for 2 seconds

    fuseBurningAnimator.start(bomb, 2000);

    // wait for 3 seconds, then explode for 1 second

    setTimeout(function() {
        explosionAnimator.start(bomb, 1000);

        // wait for 2 seconds, then reset to the
        // original bomb image

        setTimeout(function() {
            bomb.painter = bombPainter;
        }, 2000);
    }, 3000);
};

function animate(now) {
    context.clearRect(0, 0, canvas.width, canvas.height);
    bomb.paint(context);
    requestAnimationFrame(animate);
}

bomb.left = LEFT;
bomb.top = TOP;
bomb.width = WIDTH;
bomb.height = HEIGHT;

for (let i = 0; i < NUM_FUSE_PAINTERS; ++i) {
    fuseBurningPainters.push(new ImagePainter(`fuse-0${i}.png`));
}

for (let i = 0; i < NUM_EXPLOSION_PAINTERS; ++i) {
    explosionPainters.push(new ImagePainter(`explosion-0${i}.png`));
}

requestAnimationFrame(animate);
